<template>
  <van-icon
    :color="collected ? 'green' : '#777'"
    :name="collected ? 'star' : 'star-o'"
    @click="onCollected"
  />
</template>

<script>
import { addArticleCollected, deleteArticleCollected } from '@/api/article.js'
export default {
  data () {
    return {

    }
  },

  // 配置v-model的解析规则
  model: {
    // 属性解析为collected
    prop: 'collected'
  },

  props: {
    collected: {
      type: Boolean,
      required: true
    },
    // 父组件的文章id
    articleId: {
      type: [Number, Object],
      required: true
    }
  },

  created () {

  },

  methods: {
    async onCollected () {
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 0 // 持续展示 toast
      })
      try {
        if (this.collected) {
          // 已经收藏 实现取消收藏
          await deleteArticleCollected(this.articleId)
        } else {
          // 未收藏 实现添加收藏
          await addArticleCollected(this.articleId)
        }
        this.$toast('操作成功')
        this.$emit('input', !this.collected)
      } catch (err) {
        this.$toast('操作失败')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
